<?php
namespace Admin\Controller;
require __DIR__ . './../../../simplewind/Core/Library/Vendor/jpush/autoload.php';
use Common\Model\LiveModel;
use Common\Model\NewsCommentModel;
use Common\Model\NewsModel;
use Common\Model\UserMerssageModel;
use JPush\Client as JPush;



use JPush\Exceptions\APIConnectionException;
use Think\Cache\Driver\Redis;
use Think\Controller;
use Think\Log;

class PushController extends Controller
{
    //推送 消息
    function push_all()
    {
        //查找 数据库中 发送中的 消息
        $push_sel = new UserMerssageModel();
        $push_one = $push_sel->where("send_status='1' and status = 1")
            ->order("create_date asc ")
            ->limit(1)
            ->find();
        if($push_one) {
            /*
             * 开发、仿真:
             * app_key:    2d813307a3b53caa4835c7ab
             * secret:     5ef7c9511ab47a793b1f4027
             * 生产：
             * app_key:    bb15edb8b0a59a3e172b4ea0
             * secret:     ca206e50e6a37e0174dec8c2
            */
            $app_key = C('app_key');
            $master_secret = C('master_secret');

//        $registration_id = '171976fa8a8974a6b0d';

            $client = new JPush($app_key, $master_secret);

            if ($push_one['news_type'] == 8) {
                //直播类型 获取URL中的id 值 放入news_id 内
                $news_id_pos = strrpos($push_one['url'], 'id=') + 3;
                $news_id_str = substr($push_one['url'], $news_id_pos);
                $news_out_pos = strpos($news_id_str, '&');
            } else {
                if($push_one['cityname']){
                    $user_area = M("vruser1.user_area_push", null);
                    $user_list = $user_area->join("vruser1.user u on u.user_id = user_area_push.user_id",'left')
                        ->where("user_area_push.area='".$push_one['cityname']."'")
                        ->field('registration_id')
                        ->select();
                    $user_registration = array_column($user_list, 'registration_id');
                    $user_registration = array_values(array_filter($user_registration));
                }
                if (!strrpos($push_one['url'], 'news_id=')) {
                    //URL 内没有 news_id
                    $news_id = '';
                } else {
                    //找到 news_id= 位置
                    $news_id_pos = strrpos($push_one['url'], 'news_id=') + 8;
                    //截取 news_id  后内容
                    $news_id_str = substr($push_one['url'], $news_id_pos);
                    //截取到 & 首次出现位置  若没有 截取后面的全部
                    $news_out_pos = strpos($news_id_str, '&');
                }
            }
            if ($news_out_pos) {
                $news_id = substr($news_id_str, 0, $news_out_pos);
            } else {
                $news_id = $news_id_str;
            }

            try {
                if(count($user_registration) > 0){
                    $push_payload = $client->push()
//                        ->setPlatform('all')
//                        ->addAllAudience()
                        ->setPlatform(array('ios', 'android'))
                        ->addRegistrationId($user_registration)
//                        ->addAlias($user_registration)
                        ->iosNotification($push_one['title'], array(
                            'extras' => array(
                                'new_type' => $push_one['news_type'],
                                'new_id' => $news_id
                            )
                        ))
                        ->androidNotification($push_one['title'], array(
                            'extras' => array(
                                'new_type' => $push_one['news_type'],
                                'new_id' => $news_id
                            )
                        ))
//                ->setNotificationAlert($push_one['title'])
                        ->message('message content', array(
                            'title' => 'hello jpush',
                            'content_type' => 'text',
                            'extras' => array(
                                'new_type' => $push_one['news_type'],
                                'new_id' => $news_id
                            ),
                        ))
                        ->options(array(
                            'apns_production' => C('push'),
                        ))
                        ->send();
                }else {
                    $push_payload = $client->push()
                        ->setPlatform('all')
                        ->addAllAudience()
//                ->setPlatform(array('ios', 'android'))
//                ->addRegistrationId($registration_id)
                        ->iosNotification($push_one['title'], array(
                            'extras' => array(
                                'new_type' => $push_one['news_type'],
                                'new_id' => $news_id
                            )
                        ))
                        ->androidNotification($push_one['title'], array(
                            'extras' => array(
                                'new_type' => $push_one['news_type'],
                                'new_id' => $news_id
                            )
                        ))
//                ->setNotificationAlert($push_one['title'])
                        ->message('message content', array(
                            'title' => 'hello jpush',
                            'content_type' => 'text',
                            'extras' => array(
                                'new_type' => $push_one['news_type'],
                                'new_id' => $news_id
                            ),
                        ))
                        ->options(array(
                            'apns_production' => C('push'),
                        ))
                        ->send();
                }
                //更改 推送状态 为发送成功
                $data['status'] = 2;
                $res = $push_sel->where("id = " . $push_one['id'])->data($data)->save();
                echo "成功";
                print_r($res);
            } catch (APIConnectionException $e) {
                //更改 推送状态 为发送失败
                $data['status'] = 3;
                $res = $push_sel->where("id = " . $push_one['id'])->data($data)->save();
                echo "失败";
                print_r($res);
            }catch(\Exception $e) {
                //更改 推送状态 为发送失败
                $data['status'] = 3;
                $res = $push_sel->where("id = " . $push_one['id'])->data($data)->save();
                echo "失败";
                print_r($res);
            }
        }
    }

    /*
     * 预约直播 用户推送
     *
     * */
    function push_ordered_live()
    {
        //判断 是否有 redis的 进程状态值 ，没有则创建
        $redis = new  Redis();
        $password = C("REDIS_PASSWORD");
        if($password){
            $redis->auth($password);
        }
        $if_redis = $redis->get("push_status");
        \Think\Log::record("redis_status".$if_redis,"INFO");
        if (!$if_redis) {
            //新创建 进程状态 并开始执行
            $redis->set("push_status", 1);
            $this->live_push();
        } else {
            //判断 redis 缓存 进程 值是否为 0 未占用，1被占用(执行中)
            if ($if_redis == 1) { //结束此进程
                \Think\Log::record("redis_1_exit".$if_redis,"INFO");
                exit();
            } else {
                $this->live_push();
            }
        }
    }

    public function live_push(){
        $redis = new  Redis();
        $password = C("REDIS_PASSWORD");
        if($password){
            $redis->auth($password);
        }

        //查找 距离直播开始 10分钟内 的直播
        $lives = M("vrlive.live",null);
        $date_now   = time();
        $date_befor = time()+(10*60);

        $ready_lives = $lives
            ->where(" (status = 1 or status = 3) and (UNIX_TIMESTAMP(start_time) <= ".$date_befor." and UNIX_TIMESTAMP(start_time) >=".$date_now.")")
            ->select();

        $app_key       = C('app_key');
        $master_secret = C('master_secret');

        $client = new JPush($app_key, $master_secret);

        if(!empty($ready_lives)){
            \Think\Log::record("ready_lives_notnull","INFO");
            foreach ($ready_lives as $key=>$val){
                //查看 预约数据
                $orderd = M("vrlive.live_user_subscribe",null);
                $is_orderd = $orderd
                    ->field("user_id")
                    ->where(" live_id = ".$val['live_id']." and status = 1 and push_status = 0 ")
                    ->select();

                if(!empty($is_orderd)){
                    $is_orderds = implode(',', array_column($is_orderd, 'user_id'));
                    \Think\Log::record($key."---".$val['live_id']."---is_orderd_notnull","INFO");
                    $user  = M("vruser1.user",null);
                    $users = $user
                        ->field("registration_id")
                        ->where(" user_id in(".$is_orderds.") and status = 1 and registration_id is not null and registration_id != ''")->select();

                    if(!empty($users)){
                        $regs  = array_column($users,'registration_id');
                        \Think\Log::record("---aaaaaaaaaaa".$regs,"INFO");
                        \Think\Log::record($key."---".$val['live_id']."---reg_notnull","INFO");
                        try {
                            $push_payload = $client->push()
                                ->setPlatform('all')
                                ->addRegistrationId($regs)
                                ->iosNotification($val['name'], array(
                                    'extras' => array(
                                        'new_type' => 8,
                                        'new_id'   => $val['live_id']
                                    )
                                ))
                                ->androidNotification($val['name'], array(
                                    'extras' => array(
                                        'new_type' => 8,
                                        'new_id'   => $val['live_id']
                                    )
                                ))
                                ->message('message content', array(
                                    'title' => 'hello jpush',
                                    'content_type' => 'text',
                                    'extras' => array(
                                        'new_type' => 8,
                                        'new_id' => $val['live_id']
                                    ),
                                ))
                                ->options(array(
                                    'apns_production' => C('push'),
                                ))
                                ->send();

                            //更改 推送状态 为发送成功
                            $live_order = M("vrlive.live_user_subscribe",null);
                            $data['push_status'] = 1;
                            $res = $live_order->where("live_id = " . $val['live_id'])->data($data)->save();
//                    echo "成功";
                            \Think\Log::record($key."---".$val['live_id']."---推送成功","INFO");

                            \Think\Log::record($key."---".$val['live_id']."---res_".$res,"INFO");
                            print_r($res);
                        } catch (APIConnectionException $e) {
                            //更改 推送状态 为发送失败
                            \Think\Log::record($key."---".$val['live_id']."---推送失败","INFO");
                            print_r("失败");
                            continue;
                        }
                    }else{
                        \Think\Log::record($key."---".$val['live_id']."---reg_isnull","INFO");
                        continue;
                    }
                }else{
                    \Think\Log::record($key."---".$val['live_id']."---is_orderd_isnull","INFO");
                    continue;
                }
            }
            $redis->set("push_status", 0);
            return true;
        }else{
            \Think\Log::record("ready_lives_isnull","INFO");
            $redis->set("push_status", 0);
            return true;
        }
    }


    /*
     * 定时发布新闻
     *
     * */
    public function publish_news(){
        $news = M("vrnews1.news",null);
        $now = time();
        //查看符合条件 发布的新闻
        $ready_pub = $news->where("status = 2 and refresh_time <= ".$now)->select();

        $redis = new  Redis();
        $password = C("REDIS_PASSWORD");
        if($password){
            $redis->auth($password);
        }

        if(!empty($ready_pub)){
            foreach ($ready_pub as $key=>$val){
                if($val['refresh_time']) {
                    $if_redis = $redis->get("news_id-" . $val['news_id']);
                    if ($if_redis) {
                        //将缓存 更新到数据
                        $if_redis['status'] = 0;
                        $news->where('news_id=' . $val['news_id'])->save($if_redis);

                        //清除缓存
                        $redis->delete("news_id-" . $val['news_id']);
                    }
                    //将定时发布 改为 已发布状态 更新创建时间
                    $time_str = ",create_time = '".date("Y-m-d H:i:s")."',refresh_time=".$now;
                    $sql = "update vrnews1.news set status = 0".$time_str." where news_id = " . $val['news_id'];
                    $news->execute($sql);

                    //生成 静态页面
                    if($val['type'] == 5){
                        //图集
                        ob_start();

                        $share = C("admin_host").'/photos/' . $val['news_id'] . '.html';
                        $file_name = SITE_PATH.'/data/html/photos/'.$val['news_id'].'.html';
                        require_once (SITE_PATH.'/template/images_batch.html');
                        $content = ob_get_contents();
                        if(!$content){
                            \Think\Log::record("生产静态页面失败" . $val['news_id'], "INFO");
                        }
                        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';
                        $wx_appKey    = C("wx_appKey");
                        $wx_appSecret = C("wx_appSecret");
                        $jssdk = new JssdkController($wx_appKey, $wx_appSecret);
                        $signPackage = $jssdk->GetSignPackage();
                        $appId = $signPackage["appId"];
                        $timestamp = $signPackage["timestamp"];
                        $nonceStr = $signPackage["nonceStr"];
                        $signature = $signPackage["signature"];
                        $description = $val['abstract'] ? $val['abstract'] : 'live.lawnewsw.com';
                        if(!empty($val['reference_type']) && intval($val['reference_type']) == 1 && !empty($val['reference_id'])){
                            //查看 被引用图集信息
                            $ref_news = News::find()->where(['news_id'=>$val['reference_id']])->asArray()->one();
                            if(!empty($ref_news['content'])){
                                $ref_news['content'] = json_decode($ref_news['content']);
                                $contents = array();
                                foreach ($ref_news['content'] as $re_k=>$re_v){
                                    if($re_k < 3) {
                                        if(is_object($ref_news['content'][$re_k])){
                                            $str_con = substr($ref_news['content'][$re_k]->img,-2);
                                            if($str_con == '/s'){
                                                $contents[$re_k]->img = substr($ref_news['content'][$re_k]->img,0,-2);
                                            }else{
                                                if($contents[$re_k]['content']=='""'){
                                                    $tmp = $re_v->img ? $re_v->img . '?imageMogr2/thumbnail/224x150!' : '';
                                                    $contents[$re_k]['content'] = array($re_k=>array('img'=>$tmp));
                                                }else{
                                                    $contents[$re_k]['content'][$re_k]['img'] = $re_v->img ? $re_v->img . '?imageMogr2/thumbnail/224x150!' : '';
                                                }
                                            }
                                        }else {
                                            $str_con = substr($ref_news['content'][$re_k]['img'],-2);
                                            if($str_con == '/s'){
                                                $contents[$re_k]['img'] = substr($ref_news['content'][$re_k]['img'],0,-2);
                                            }
                                            $contents[$re_k]['img'] = $re_v['img'] ? $re_v['img'] . '?imageMogr2/thumbnail/224x150!' : '';
                                        }
                                    }
                                }
                            }
                        }else {
                            $contents = json_decode($val['content'], true);
                        }
                        if($val['new_title']){
                            $title = $val['new_title'];
                        }else{
                            $title = $val['title'];
                        }
                        if($val['new_cover_image']){
                            $cover_img =  $val['new_cover_image'];
                        }else{
                            if($val['cover_image']){
                                $cover_img = $val['cover_image'];
                            }else{
                                $cover_img = C('h5_host').'/public/H5/images/default.png';
                            }
                        }
                        if($val['new_cover_image']){
                            $news_cover_img =  $val['new_cover_image'];
                        }else{
                            if($val['cover_image']){
                                $news_cover_img =  $val['cover_image'];
                            }else{
                                $news_cover_img =  C('h5_host').'/public/H5/images/default.png';
                            }
                        }
                        if($val['new_abstract']){
                            $new_abstract = $val['new_abstract'];
                        }else{
                            if($val['abstract']){
                                $new_abstract = $val['abstract'];
                            }else{
                                $new_abstract = 'live.lawnewsw.com';
                            }
                        }
                        $text = '';
                        $news_content = '';
                        if($contents) {
                            foreach ($contents as $k => $v) {
                                $text .= '<img src="' . $v['img'] . '" name="' . $k . '" onclick="clickImage()">';
                            }
                            foreach ($contents as $keys => $value) {
                                $news_content .= '<div class="neirong" ';
                                if ($keys == 0) {
                                    $news_content .= 'style="display:block;" ';
                                }
                                $news_content .= '><div class="biaoti">
                        <div class="left">' . $val['title'] . '</div>
                        <div class="right"></div>
                    </div>
                    <p>' . $value['text'] . '</p>
                </div>';
                            }
                        }
                        $h5_host = C("h5_host");
                        $host    = C("host");
                        $content = str_replace('{{appId}}',$appId ,$content );
                        $content = str_replace('{{timestamp}}',$timestamp ,$content );
                        $content = str_replace('{{nonceStr}}',$nonceStr ,$content );
                        $content = str_replace('{{signature}}',$signature ,$content );
                        $content = str_replace('{{title}}',$title ,$content );
                        $content = str_replace('{{share}}',$share ,$content );
                        $content = str_replace('{{description}}',$description ,$content );
                        $content = str_replace('{{cove_img}}',$cover_img ,$content );
                        $content = str_replace('{{new_cover_img}}',$news_cover_img ,$content );
                        $content = str_replace('{{text}}',$text ,$content );
                        $content = str_replace('{{abstract}}',$new_abstract ,$content );
                        $content = str_replace('{{content}}',$news_content ,$content );
                        $content = str_replace('{{h5_host}}',$h5_host ,$content );
                        $content = str_replace('{{host}}',$host ,$content );
                        file_put_contents($file_name, $content);
                        ob_end_clean();
                    }else{
                        ob_start();

                        $share = C("admin_host").'/text/' . $val['news_id'] . '.html';
                        $file_name = SITE_PATH.'/data/html/text/'.$val['news_id'].'.html';
                        require_once (SITE_PATH.'/template/image_text_batch.html');
                        $content = ob_get_contents();
                        if(!$content){
                            \Think\Log::record("生产静态页面失败" . $val['news_id'], "INFO");
                        }
                        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';

                        $wx_appKey    = C("wx_appKey");
                        $wx_appSecret = C("wx_appSecret");
                        $jssdk = new JssdkController($wx_appKey, $wx_appSecret);
                        $signPackage = $jssdk->GetSignPackage();
                        $appId = $signPackage["appId"];
                        $timestamp = $signPackage["timestamp"];
                        $nonceStr = $signPackage["nonceStr"];
                        $signature = $signPackage["signature"];
//            $share = C("admin_host").'/text/' . $data['news_id'] . '.html';
                        if($val['new_abstract']){
                            $description = $val['new_abstract'];
                        }else{
                            if($val['abstract']){
                                $description =  $val['abstract'];
                            }else{
                                $description =  'live.lawnewsw.com';
                            }
                        }
                        if($val['new_cover_image']){
                            $cover_img =  $val['new_cover_image'];
                        }else{
                            if($val['cover_image']){
                                $cover_img = $val['cover_image'];
                            }else{
                                $cover_img = C('h5_host').'/public/H5/images/default.png';
                            }
                        }
                        if($val['new_cover_image']){
                            $news_cover_img =  $val['new_cover_image'];
                        }else{
                            if($val['cover_image']){
                                $news_cover_img =  $val['cover_image'];
                            }else{
                                $news_cover_img =  C('h5_host').'/public/H5/images/default.png';
                            }
                        }
                        if($val['new_abstract']){
                            $new_abstract = $val['new_abstract'];
                        }else{
                            if($val['abstract']){
                                $new_abstract = $val['abstract'];
                            }else{
                                $new_abstract = 'live.lawnewsw.com';
                            }
                        }
                        $time = date('m月d日 H:i',strtotime(date("Y-m-d H:i:s")));
                        if($val['source_name']) {
                            $source = '来源：<span ><a style="color:#129aee; display:inline;" href="#" onclick="toSourceId(\'' . $val["source_id"] . '\',\'' . $val["source_name"] . '\')" >' . $val["source_name"] . '</a></span>';
                        }else{
                            $source = '';
                        }

                        $news_content = json_decode($val['content']);

                        if(!empty($val['outer_url'])) {
                            $out_url = '<div class="ReadText" style="float:right;margin:0 5%;font-size:1.3rem"><a href="' . $val['outer_url'] . '" style="color: #2ea7e0;">阅读原文</a></div>';
                        }else{
                            $out_url = '';
                        }
                        if($val['new_title']){
                            $title = $val['new_title'];
                        }else{
                            $title = $val['title'];
                        }
                        if(isset($data['external_link'])){
                            $external_link = $data['external_link'];
                        }
                        $h5_host = C("h5_host");
                        $host    = C("host");
                        $content = str_replace('{{appId}}',$appId ,$content );
                        $content = str_replace('{{timestamp}}',$timestamp ,$content );
                        $content = str_replace('{{nonceStr}}',$nonceStr ,$content );
                        $content = str_replace('{{signature}}',$signature ,$content );
                        $content = str_replace('{{share}}',$share ,$content );
                        $content = str_replace('{{description}}',$description ,$content );
                        $content = str_replace('{{title1}}',$title ,$content );
                        $content = str_replace('{{cove_img}}',$cover_img ,$content );
                        $content = str_replace('{{new_cover_image}}',$news_cover_img ,$content );
                        $content = str_replace('{{title}}',$val['title'] ,$content );
                        $content = str_replace('{{abstract}}',$new_abstract ,$content );
                        $content = str_replace('{{data}}',$time ,$content );
                        $content = str_replace('{{source}}',$source ,$content );
                        $content = str_replace('{{content}}',$news_content ,$content );
                        $content = str_replace('{{out_url}}',$out_url ,$content );
                        $content = str_replace('{{h5_host}}',$h5_host ,$content );
                        $content = str_replace('{{host}}',$host ,$content );
                        $content = str_replace('{{external_link}}',$external_link ,$content );
                        file_put_contents($file_name, $content);
                        ob_end_clean();
                    }
                    
                    // 根据时间 更新 列表
                    $redis = new Redis();
                    if($val['column_id'] != 0){
                        $column_ids = $val['column_id'];
                        $is_area = 0;
                    }else if($val['area_id'] != 0){
                        $column_ids  = $val['area_id'];
                        $is_area = 1;
                    }
                    if($val['special_news_id'] != 0){
                        $name = C('environment')."_special_list_" . $val['special_news_id'] . '_update';
                        $column_list = C('environment').'_new_list_'.$is_area.'_'.$column_ids.'_update';
                        $column_key = $redis->buildKey($column_list);
                        $redis->set_redis($column_key, time());
                    }else{
                        $name = C('environment').'_new_list_'.$is_area.'_'.$column_ids.'_update';
                    }
                    $key = $redis->buildKey($name);
                    $redis->set_redis($key, time());
                    $info = $redis->get_redis($key);

                    \Think\Log::record("定时发布的新闻成功" . $val['news_id'], "INFO");
                }
            }
            \Think\Log::record("定时发布的新闻发布完成","INFO");
        }else{
            \Think\Log::record("无需要定时发布的新闻","INFO");
        }

    }



    /*
     * 定时 清新闻 草稿、定时发布缓存
     * 超过30天的
     * */
    public function clear_trash(){
        //查看数据 创建时间 超过十天的
        $news = M("vrnews1.news",null);
        $date_now   = time();
        $date_befor = (time()+(24*60*60))*30;

        $ready_news = $news
            ->where(" (status != 0) and ( ".$date_now." - UNIX_TIMESTAMP(create_time) > ".$date_befor." )")
            ->select();
        $redis = new  Redis();
        $password = C("REDIS_PASSWORD");
        if($password){
            $redis->auth($password);
        }

        if(!empty($ready_news)){
            foreach ($ready_news as $key=>$val){
                $if_redis = $redis->get("news_id-".$val['news_id']);
                if($if_redis){
                    $redis->delete("news_id-".$val['news_id']);
                }
                $news->where(array('news_id' => $val['news_id']))->delete();
            }
            Log::record("定时 清草稿、定时发布 新闻 成功",'INFO');
            print_r("定时 清草稿、定时发布 新闻 成功");
        }else{
            print_r("无符合 的草稿等信息");
        }
    }

    /*
     * 判断 时间 已到开始时间，还未开始推流，20分钟以上 直接关闭流 直播状态改为结束
     * 状态是 直播中的  推流是断流状态 超过20分钟的，直接关闭流  默认直播为已结束
     * */
    public function check_status(){
        $live = M("vrlive.live",null);
        $now_date = date('Y-m-d H:i:s');
        //查看所有 在直播中的、 视频及视频加图文、 快直播、已开始推流的    直播信息
        $live_sel = $live
            ->join("vrlive.live_camera_angle camera on camera.live_id = live.live_id",'left')
            ->join("vrlive.live_channel channel on channel.channel_id = camera.source_id",'left')
            ->where(" category in(1,4) and is_fast = 1 and live.start_time < '".$now_date."' and live.status not in(0,2,5) and txy_channel_id !='' and  LENGTH(txy_channel_id) > 30 ")
            ->field("live.live_id,channel.txy_channel_id,push_time,live.status,live.start_time")
            ->select();
//print_r($live_sel);die;
        if(!$live_sel){
            exit();
        }

//        $url = "http://fcgi.video.qcloud.com/common_access";
        $appid = '1253999690';
        $live_api = C('API_LiveKey');
        foreach ($live_sel as $key=>$val){
            $t = time()+60*60*24;
            $sign = md5($live_api.$t);
            $Param_s_channel_id = $val['txy_channel_id'];
            $now_time = time();

            if($val['push_time'] && $val['push_time'] != 0){
                //与当前时间相比，是否 超过20分钟
                if($now_time - $val['push_time'] > 20*60){
                    //超二十分钟 关闭推流 并 将直播 状态 置为 已结束
                    $interface = "Live_Channel_SetStatus";
                    $config = array(
                        'SecretId'       => C("API_SecretId"),
                        'SecretKey'      => C("API_SecretKey"),
                        'RequestMethod'  => 'GET',
                        'DefaultRegion'  => C("API_DefaultRegion"));

                    vendor("QcloudApi.QcloudApi");
                    $service = \QcloudApi::load(\QcloudApi::MODULE_FCGI, $config);
                    $package = array(
                        'appid'=>$appid,
                        'interface'=>$interface,
                        'Param.s.channel_id'=>$Param_s_channel_id,
                        'Param.n.status'=>0,
                        't'=>$t,
                        'sign'=>$sign,
                    );

                    $res = $service->Send($package);
                    $res_json = json_decode($res,true);
                    if($res_json['ret'] != 0){
                        Log::record("关闭推流失败，直播ID=".$val['live_id'],'INFO');
                        print_r("关闭推流失败，直播ID=".$val['live_id']);
                    }
                    //更改直播状态为 已结束
                    $live->where(array('live_id'=>$val['live_id']))->save(array('status'=>2));

                    continue;
                }else{
                    continue;
                }
            }

            //获取 直播推流状态
            $interface = "Live_Channel_GetStatus";
            $config = array(
                'SecretId'       => C("API_SecretId"),
                'SecretKey'      => C("API_SecretKey"),
                'RequestMethod'  => 'GET',
                'DefaultRegion'  => C("API_DefaultRegion"));

            vendor("QcloudApi.QcloudApi");
            $service = \QcloudApi::load(\QcloudApi::MODULE_FCGI, $config);
            $package = array(
                'appid'=>$appid,
                'interface'=>$interface,
                'Param.s.channel_id'=>$Param_s_channel_id,
                't'=>$t,
                'sign'=>$sign,
            );

            $res = $service->Send($package);
            $res_json = json_decode($res,true);
            //从未 推过流
            if($res_json['ret'] == 20601){
                if($now_time - strtotime($val['start_time']) > 20*60){
                    $live->where(array('live_id'=>$val['live_id']))->save(array('status'=>2));
                }else{
                    continue;
                }
            }

            if(!empty($res_json['output'][0]['status']) || $res_json['output'][0]['status'] == 0){
                //断流  更新断流时间 push_time
                if($res_json['output'][0]['status'] == 0){
                    $live->where(array('live_id'=>$val['live_id']))->save(array('push_time'=>$now_time));
                }
                //正常推流 跳过
                if($res_json['output'][0]['status'] == 1){
                    continue;
                }

                //流关闭状态 关闭直播
                if($res_json['output'][0]['status'] == 3){
                    $live->where(array('live_id'=>$val['live_id']))->save(array('status'=>2));
                }
            }

        }
    }

    public function checkcode(){
        $appid = '1253999690';
        $live_api = C('API_LiveKey');

        $t = time()+60*60*24;
        $sign = md5($live_api.$t);
        $Param_s_channel_id = '10248_201715033800745203_1503380074';
        $now_time = time();


        //获取 直播推流状态
        $interface = "Live_Channel_GetStatus";
        $config = array(
            'SecretId'       => C("API_SecretId"),
            'SecretKey'      => C("API_SecretKey"),
            'RequestMethod'  => 'GET',
            'DefaultRegion'  => C("API_DefaultRegion"));

        vendor("QcloudApi.QcloudApi");
        $service = \QcloudApi::load(\QcloudApi::MODULE_FCGI, $config);

        $package = array(
            'appid'=>$appid,
            'interface'=>$interface,
            'Param.s.channel_id'=>$Param_s_channel_id,
            't'=>$t,
            'sign'=>$sign,
        );

        $res = $service->Send($package);
        $res_json = json_decode($res,true);
        //从未 推过流
        if($res_json['ret'] == 20601){
            echo 111;die;
        }

        if(!empty($res_json['output'][0]['status']) || $res_json['output'][0]['status'] == 0){
            //断流  更新断流时间 push_time
            if($res_json['output'][0]['status'] == 0){
                echo 222;die;
            }
            //正常推流 跳过
            if($res_json['output'][0]['status'] == 1){
               echo 333;die;
            }

            //流关闭状态 关闭直播
            if($res_json['output'][0]['status'] == 3){
                echo 444;die;
            }
        }
    }
    
    /**
     * 定时任务检查直播状态
     * @by cong.zhao
     */
    public function checkout_livestatus(){
    	$live = M("vrlive.live",null);
    	$live->where("status =2 and is_fast = 1 and rever_url is not null")->save(array('status'=>5));
    }

    /*
     * 后台 添加新 菜单 给有权限的用户 都赋予此菜单的权限
     *
     * */
    public function setadmin_role(){
        //查看 直播管理  的菜单ID
        $sys_menu = M("vradmin1.sys_menu",null);
        $menu_id = $sys_menu->where("name = '直播管理'")->field("menu_id")->select();
        $son_menu_id = $sys_menu->where("name = '采集端下载'")->field("menu_id")->select();

        //查看 有  直播管理  权限的 所有账号
        $menu_admin = M("vradmin1.sys_menu_admin",null);
        $menu_admins = $menu_admin->where("menu_id = ".$menu_id[0]['menu_id'])->field("admin_id")->select();

        //赋值
        foreach ($menu_admins as $key=>$val){
            $param['menu_id'] = $son_menu_id[0]['menu_id'];
            $param['admin_id'] = $val['admin_id'];
            $menu_admin->add($param);
        }
        echo 1;
    }

    /*
     * 过滤问题 评论回复
     * */
    public function check_comment(){
        $comment = M("vrnews1.news_comment",null);
        //查出所有符合条件的数据
        $comment_sel = $comment
            ->where(" status = 1 and is_show = 0")
            ->select();
//print_r($comment_sel);die;

        //正则过滤
        if(!empty($comment_sel)) {
            foreach ($comment_sel as $key => $val) {
//                print_r($val);die;
                $comment = M("vrnews1.news_comment", null);
                $content = trim($val['content']); //去掉两边空格
                //中文标点
                $char = "。、！？：；﹑•＂…‘’“”〝〞∕¦‖—　〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔！¡？¿﹖﹌﹏﹋＇´ˊˋ―﹫︳︴¯＿￣﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼（） ，+-~！@#￥%……&*（）{}|：“”《》？ ";

                if(preg_match("/[a-zA-Z\d]*[[:space:]]+/",$content)){
//                    echo 555;die;
                    continue;
                }else if (preg_match("/^([\x{4e00}-\x{9fa5}])/u",$content)) { //utf8 纯汉字少于6个汉字
                    if(mb_strlen($content) < 6){
//                        echo 1;die;
                        $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                        $comment->execute($sql);
                    }
                } else if (preg_match("/^[a-zA-Z]+$/", $content)) { //纯字母
//                    echo 2;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                } else if(preg_match("/^\d+$/", $content)){ // 纯数字
//                    echo 3;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                }else if(preg_match("/^([[:punct:]]|[[:space:]])+$/", $content)){ //或 纯标点符号  '! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ' { | } ~'.
//                    echo 4;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                }else if(preg_match("/^([".$char."]|[[:space:]])[^a-zA-Z\d]+$/",$content)){
//                    print_r($content);
//                    echo 42;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                }else if (preg_match("/^\[em_(\d+)\]+$/", $content)) { //表情特殊符号
//                    echo 5;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                }else if (preg_match("/^(\\\[a-zA-Z\d]+)+$/", $content)) { //纯 表情符号 \ude31
//                    echo 6;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                } else if (preg_match("/^([a-zA-Z\d]|[[:punct:]]|[".$char."])*$/", $content)) { //穿插错乱
//                    echo 7;die;
                    $sql = "update vrnews1.news_comment set is_show = 1 where comment_id = " . $val['comment_id'];
                    $comment->execute($sql);
                }

                $content = '';
            }
            return true;
        }
        return true;
    }
    
        public function change_livestatus(){
    	$live = M("vrlive.live",null);
//    	$live->where("status =2 and is_fast = 1 and rever_url is not null")->save(array('status'=>5));
        
        $tod_time = date('Y-m-d') . ' 00:00:00';
//        $sql      = 'SELECT * FROM live where create_time >"' . $tod_time . '"';
//        $live_list = $pdodb->getAll($sql);
//        $map['create_time'] >  $tod_time ;
        $map['create_time']  = array('gt',$tod_time);
        $map['status']=array('exp',' IN (1,3) ');
         
         $live_list = $live->where($map)->select();
//         echo  M("vrlive.live",null)->getLastSql();
//     print_r($live_list);exit();     
        foreach ($live_list AS $k => $v) {
        $start_time = date('Y-m-d H:i', strtotime($v['start_time']));
        if ($start_time > date('Y-m-d H:i')) {
        $live_data['status'] = 3;
        } else {
        $live_data['status'] = 1;
        }
         $live->where(array('live_id'=>$v['live_id']))->save($live_data);
//        $pdodb->doUpdate('live', $live_data, 'live_id = ' . $v['live_id']);
        }
    }



}